class CommentObserver < ActiveRecord::Observer
  def after_create(comment)
    
    update_user_points_and_votes_count(comment,1)
    
    update_owner_points(comment)
  end
  
  def after_destroy(comment)
    
    update_user_points_and_votes_count(comment,-1)
  end
  
  private
  def update_owner_points(comment)
    #find the ownler of content
    # content
    content_clazz = Kernel.const_get(comment.commentable_type)
    #get the user
    content = content_clazz.find(comment.commentable_id)
    if content.user_id!=comment.user_id
      user = User.find(content.user_id)    
      points = (user.active_campaign.points_content_commented if user.active_campaign) || WebappConstants::ACTIVITY_POINTS[:content_commented]
      user.points = 0 unless  user.points
      user.points +=points
      user.save!
      
      user_campaign = user.active_user_campaign
      if user_campaign
        user_campaign.points +=points
        user_campaign.points = 0 if user_campaign.points < 0
        user_campaign.save!  
      end        
    end
    
  end
  
  def update_user_points_and_votes_count(comment, factor)
    #get the number of points for this resource
    
    user = User.find(comment.user_id)
    #only add points if not his own content
    content_clazz = Kernel.const_get(comment.commentable_type)
    #get the user
    content = content_clazz.find(comment.commentable_id)
    
    if content.user_id!=user.id
      points = (user.active_campaign.points_comment_content if user.active_campaign) || WebappConstants::ACTIVITY_POINTS[:commenting]
      user.points = 0 unless  user.points
      user.points +=(factor*points)
      user.save!
      
      content.comment_count +=1*factor
      content.save!
      
      #update active_user_campaign, if any
      user_campaign = user.active_user_campaign
      if user_campaign
        user_campaign.points +=(factor*points)
        user_campaign.points = 0 if user_campaign.points < 0
        user_campaign.save  
      end      
    end
    
    
  end
end
